package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrderPageDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Jiang
 * @date 2022/2/19
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders>
        implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取用户的默认地址信息，判断用户是否有地址
        AddressBook add = addressBookService.getById(orders.getAddressBookId());
        if (add == null) {
            throw new CustomException("请选择一个默认收获地址！");
        }
        //拼接地址
        String addr = add.getCityName() == null ? "" : add.getCityName() +
                add.getProvinceName() == null ? "" : add.getProvinceName() +
                add.getDistrictName() == null ? "" : add.getDistrictName();
        if (addr.equals("")) {
            addr = add.getDetail();
        }
        //填充订单基本信息
        Long id = IdWorker.getId();
        orders.setId(id);
        orders.setUserId(BaseContext.getId());
        orders.setStatus(2);
        orders.setNumber(id.toString());
        orders.setPhone(add.getPhone());
        orders.setUserName(userService.getById(BaseContext.getId()).getName());
        orders.setConsignee(add.getConsignee());
        orders.setAddress(addr);
        AtomicInteger amount = new AtomicInteger(0);
        //获取购物车里的数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.selectByList();
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(s -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setId(IdWorker.getId());
            orderDetail.setImage(s.getImage());
            orderDetail.setName(s.getName());
            orderDetail.setDishId(s.getDishId());
            orderDetail.setSetmealId(s.getSetmealId());
            orderDetail.setNumber(s.getNumber());
            orderDetail.setAmount(s.getAmount());
            orderDetail.setDishFlavor(s.getDishFlavor());
            //计算总金额
            BigDecimal multiply = s.getAmount().multiply(new BigDecimal(s.getNumber()));
            //累加
            amount.addAndGet(multiply.intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //填充订单总金额
        orders.setAmount(new BigDecimal(amount.get()));
        //添加数据到订单表
        orderMapper.insert(orders);
        //添加订单详情表
        orderDetailMapper.addAll(orderDetails);
        //清除购物车
        shoppingCartService.clearShoppingCart();
    }

    @Override
    public Page<Orders> findByPage(OrderPageDto order) {
        Page<Orders> pages = new Page<>(order.getPage(), order.getPageSize());
        orderMapper.selectByPage(pages, order);
        log.info("pages ====> {}", pages);
        return pages;
    }

    @Override
    public void upStatus(Orders orders) {
        LambdaUpdateWrapper<Orders> lup = Wrappers.lambdaUpdate(Orders.class);
        lup.eq(Orders::getId, orders.getId());
        lup.set(Orders::getStatus, orders.getStatus());
        orderMapper.update(orders, lup);
    }

    @Override
    public Page<OrdersDto> findUserPage(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.lambdaQuery(Orders.class);
        queryWrapper.eq(Orders::getUserId, BaseContext.getId());
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        orderMapper.selectPage(ordersPage, queryWrapper);
        List<OrdersDto> ordersDtos = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            //拷贝属性
            BeanUtils.copyProperties(orders, ordersDto);
            //查
            LambdaQueryWrapper<OrderDetail> qw = Wrappers.lambdaQuery(OrderDetail.class);
            qw.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(qw);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }

    @Override
    public void orderAgain(Orders orders) {
        //获取这个订单的信息
        LambdaQueryWrapper<OrderDetail> qw = Wrappers.lambdaQuery(OrderDetail.class);
        qw.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(qw);
        orderDetails.stream().forEach(orderDetail -> {
            //进行修改操作
            LambdaUpdateWrapper<ShoppingCart> suw = Wrappers.lambdaUpdate(ShoppingCart.class);
            suw.set(ShoppingCart::getNumber,orderDetail.getNumber());
            //设置条件
            suw.eq(ShoppingCart::getUserId,BaseContext.getId())
                    .eq(orderDetail.getDishId() != null,ShoppingCart::getDishId,orderDetail.getDishId())
                    .eq(orderDetail.getSetmealId() != null,ShoppingCart::getSetmealId,orderDetail.getSetmealId());
            //执行修改
            boolean result = shoppingCartService.update(suw);
            if(!result){
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setUserId(BaseContext.getId());
                shoppingCart.setNumber(orderDetail.getNumber());
                shoppingCart.setName(orderDetail.getName());
                shoppingCart.setImage(orderDetail.getImage());
                shoppingCart.setDishId(orderDetail.getDishId());
                shoppingCart.setSetmealId(orderDetail.getSetmealId());
                shoppingCart.setAmount(orderDetail.getAmount());
                shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
                //进行添加
                shoppingCartService.addShoppingCart(shoppingCart);
            }
        });
    }


}
